<?php

namespace App\Http\Controllers\Exp;

use App\Http\Controllers\Controller;
use App\Models\Exp;
use Auth;
use Illuminate\Http\Request;
use App\Http\Requests\Exp\ExpRequest;

class ExpController extends Controller
{
    /**
     * 创建经验
     * @param ExpRequest $request
     * @return mixed
     */
    public function create(ExpRequest $request)
    {
        $type = $request->get('type', 'create');
        $user = Auth::guard('api')->user();
        $request->merge(['user_id' => $user->id]);
        $request['use_skill'] = json_encode($request['use_skill']);
        $request['res_job'] = json_encode($request['res_job']);

        if($type === 'create') {
            Exp::create($request->all());
            return $this->success('创建成功', null);
        } else if($type === 'update') {
            $id = $request->get('id');
            if($exp = Exp::where('id', $id)->first()) {
                $exp->update($request->all());
                return $this->success('更新成功', null);
            }
            return $this->error('未找到数据', null);
        }

        return $this->unValidate('未找到类型');
    }

    /**
     * 获取列表
     * @return mixed
     */
    public function list(Request $request)
    {
        $user = Auth::guard('api')->user();
        $data = array();

        $hidden = $request->get('type', 'hidden');
        $hidden === 'hidden' && ($data['hidden'] = 0);
        $hidden === 'show' && ($data['hidden'] = 1);

        $list = Exp::where('user_id', $user ? $user->id : 1)->where($data)->get();
        return $this->success('创建成功', $list);
    }

    /**
     * 切换是否启用
     * @param Exp $exp
     * @return mixed
     */
    function switch(Exp $exp)
    {
        $exp->hidden = $exp->hidden ? 0 : 1;
        $exp->save();
        return $this->success('修改成功', null);
    }
}
